//正式数据库和测试数据库表比对

var db = require('../mysql/dbhelper1.js');
var dbdev = require('../mysql/dbhelper2.js');
var Q = require('q');
const lodash = require('lodash');

let dbcheck_gettables = async opt=>{
	console.log("dbcheck_gettables");
	let p = Q.defer();
	let sql="SHOW TABLES"
	let tables = await db.getTableJsonAll(sql)
	let tablesDev = await dbdev.getTableJsonAll(sql)
	let tableDic={},tableDevDic={};
	
	
	for(let t of tables){
		for(let k in t){
			tableDic[t[k]]={name:t[k],differ:false,columns:[]}
		}
	}
	
	for(let t of tablesDev){
		for(let k in t){
			tableDevDic[t[k]]={name:t[k],differ:false,columns:[]}
		}
	}
	
	
	//检查表数量是否一致
	
	for(let t in tableDic){
		if(!tableDevDic[t]){
			tableDic[t].differ=true
		}
	}
	
	for(let t in tableDevDic){
		if(!tableDic[t]){
			tableDevDic[t].differ=true
		}
	}
	// console.log(tableDic)
	// console.log(tableDevDic)
	
	// return p.promise
	
	//获取表结构
	for(let t in tableDic){
		sql="SHOW COLUMNS FROM "+t
		
		tableDic[t].columns = await db.getTableJsonAll(sql)
		tableDic[t].colDic={}
		for(let c of tableDic[t].columns){
			c.differ = false
			tableDic[t].colDic[c.Field] = c
		}
		

	}
	
	
	for(let t in tableDevDic){
		sql="SHOW COLUMNS FROM "+t
		tableDevDic[t].colDic={}
		try{
			tableDevDic[t].columns = await dbdev.getTableJsonAll(sql)
			for(let c of tableDevDic[t].columns){
				c.differ = false
				
				tableDevDic[t].colDic[c.Field] = c
			}
		}catch(e){
			console.log(e)
		}
	}

	
	//检查表数量是否一致
	for(let t in tableDic){
		if(tableDevDic[t]){
			for(let k in tableDevDic[t].colDic){
				if(tableDic[t].colDic[k]){
					//检查两个字段是否一致
					if(!lodash.isEqual(tableDic[t].colDic[k], tableDevDic[t].colDic[k])){
						tableDevDic[t].colDic[k].differ = true
						tableDevDic[t].differ = true
					}
				}else{
					tableDevDic[t].colDic[k].differ = true
					tableDevDic[t].differ = true
				}
			}
		}else{
			tableDic[t].differ = true
		}
	}
	
	for(let t in tableDevDic){
		if(tableDic[t]){
			for(let k in tableDic[t].colDic){
				if(tableDevDic[t].colDic&&tableDevDic[t].colDic[k]){
					//检查两个字段是否一致
					if(!lodash.isEqual(tableDic[t].colDic[k], tableDevDic[t].colDic[k])){
						tableDic[t].colDic[k].differ = true
						tableDic[t].differ = true
					}
				}else{
					tableDic[t].colDic[k].differ = true
					tableDic[t].differ = true
				}
			}
		}else{
			tableDevDic[t].differ = true
		}
	}
	
	let tabelArr=[],tableDevArr=[];
	for(let t in tableDic){
		delete tableDic[t].colDic
		tabelArr.push(tableDic[t])
	}
	
	for(let t in tableDevDic){
		delete tableDevDic[t].colDic
		tableDevArr.push(tableDevDic[t])
	}
	
	p.resolve({tablePro:tabelArr,tableDev:tableDevArr})
	return p.promise;
	
	
	
}


module.exports = {
	dbcheck_gettables,
	
	}